package com.example.springboot.mybatisflex.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.example.springboot.mybatisflex.entity.TransactionData;
import com.example.springboot.mybatisflex.mapper.TransactionDataMapper;
import com.example.springboot.mybatisflex.service.forest.TransactionDataForest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author wwl
 * @version 1.0
 * @date 2024/10/18 11:45
 * @description:
 */
@Slf4j
@Service
public class TransactionDataService {
    @Autowired
    private TransactionDataForest transactionData;
    @Autowired
    private TransactionDataMapper transactionDataMapper;
    private String myUrl = "data_tab_daily_yyyyMMddc.js";

    /**
     * SELECT
     * 	stock_code,
     * 	stock_name,
     * 	sum(buy_turnover),
     * 	sum(sell_turnover),
     * 	sum(total_turnover),
     * 	sum(net_inflows) AS net_inflows,
     * 	date,
     * 	create_time
     * FROM
     * 	transaction_data
     * WHERE
     * 	date = "2024-10-18"
     * GROUP BY
     * 	stock_code
     * ORDER BY
     * 	net_inflows DESC;
     */

    public void findData() {
        LocalTime now = LocalTime.now();
        LocalDate nowDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        if (now.getHour() < 17) {
            // 获取前一天的日期
            nowDate = nowDate.minusDays(1);
        }
        String formattedDate = nowDate.format(formatter);
        String url = myUrl.replace("yyyyMMdd", formattedDate);
        String data = transactionData.getData(System.currentTimeMillis(), url);
        if (!StringUtils.isEmpty(data) && data.contains("tabData =")) {
            List<TransactionData> addList = new ArrayList<>();
            String dateStr = null;
            JSONArray jsonArray = JSONArray.parseArray(data.replaceFirst("tabData =", ""));
            for (Object item : jsonArray) {
                JSONObject jsonObject1 = (JSONObject) item;
                JSONArray jsonArray1 = jsonObject1.getJSONArray("content");
                dateStr = jsonObject1.getString("date");
                for (Object item1 : jsonArray1) {
                    JSONObject jsonObject2 = (JSONObject) item1;
                    if (jsonObject2.getString("style").equals("2")) {
                        JSONObject table = jsonObject2.getJSONObject("table");
                        JSONArray jsonArray3 = table.getJSONArray("tr");
                        for (Object item3 : jsonArray3) {
                            JSONObject jsonObject3 = (JSONObject) item3;
                            JSONArray jsonArray4 = jsonObject3.getJSONArray("td");
                            for (Object item4 : jsonArray4) {
                                Date date = new Date();
                                JSONArray array = (JSONArray) item4;
                                TransactionData transaction = new TransactionData();
                                transaction.setRank(array.getString(0));
                                transaction.setStockCode(array.getString(1));
                                transaction.setStockName(array.getString(2).trim());
                                transaction.setDate(dateStr);
                                transaction.setCreateTime(date);
                                if (array.size() == 4) {
                                    transaction.setType(1);
                                    transaction.setTotalTurnover(Long.parseLong(array.getString(3).replace(",", "")));
                                } else if (array.size() == 6) {
                                    transaction.setType(2);
                                    Long buy = Long.parseLong(array.getString(3).replace(",", ""));
                                    Long sell = Long.parseLong(array.getString(4).replace(",", ""));
                                    transaction.setBuyTurnover(buy);
                                    transaction.setSellTurnover(sell);
                                    transaction.setTotalTurnover(Long.parseLong(array.getString(5).replace(",", "")));
                                    transaction.setNetInflows(buy - sell);
                                }
                                addList.add(transaction);
                                log.info("数据：{}", JSON.toJSONString(item4));
                            }
                        }
                    }
                }
            }
            if (!CollectionUtils.isEmpty(addList)) {
                log.info("查询到数据:{}", JSON.toJSONString(addList));
                if (!StringUtils.isEmpty(dateStr)) {
                    Map<String, Object> whereConditions = new HashMap<>();
                    whereConditions.put("date", dateStr);
                    transactionDataMapper.deleteByMap(whereConditions);
                }
                transactionDataMapper.insertBatch(addList);
            }
        }


    }

}
